package com.itheima.ydd.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.ydd.common.ResultData;
import com.itheima.ydd.dto.SysRoleDto;
import com.itheima.ydd.entity.SysRole;
import com.itheima.ydd.service.ISysRoleService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;

/**
 * <p>
 * 角色表 前端控制器
 * </p>
 *
 * @author author
 * @since 2022-05-22
 */
@RestController
@Slf4j
@RequestMapping("/sys_role")
public class SysRoleController {
    @Autowired
    private ISysRoleService iSysRoleService;

    /**
     * 添加角色
     * @param hashMap
     * @return
     */
    @PostMapping("/add")
    public ResultData add(@RequestBody HashMap<String, Object> hashMap) {
        log.info(hashMap.toString());
        return iSysRoleService.addSysRole(hashMap);
    }

    /**
     * id删除
     * @param id
     * @return
     */
    @GetMapping("/del")
    public ResultData del(String id) {
        iSysRoleService.removeById(id);
        return ResultData.ok("删除成功",null);
    }

    /**
     * 更新角色
     * @param hashMap
     * @return
     */
    @PostMapping("/update")
    public ResultData update(@RequestBody HashMap<String, Object> hashMap) {
        log.info(hashMap.toString());
        iSysRoleService.updateSysRole(hashMap);
        return ResultData.ok("",null);
    }

    /**
     * 角色列表
     * @return
     */
    @GetMapping("/allData")
    public ResultData allData() {
        List<SysRole> list = iSysRoleService.list();

        return ResultData.ok("",list);
    }

    /**
     * id查询
     *
     * @param id
     * @return
     */
    @GetMapping("/rowInfo")
    public ResultData rowInfo(String id) {
        SysRoleDto sysRoleDto = iSysRoleService.rowInfo(id);
        return ResultData.ok("", sysRoleDto);
    }

    /**
     * 分页查询
     *
     * @param name
     * @param page
     * @param limit
     * @return
     */
    @GetMapping("/list")
    public ResultData list(String name, String page, String limit) {

        //构造分页构造器
        Page page1 = new Page(Long.valueOf(page), Long.valueOf(limit));

        //构造条件构造器
        LambdaQueryWrapper<SysRole> queryWrapper = new LambdaQueryWrapper();
        //添加过滤条件
        queryWrapper.like(StringUtils.isNotEmpty(name), SysRole::getName, name);
        //添加排序条件
        queryWrapper.orderByDesc(SysRole::getUpdateDate);

        //查询
        iSysRoleService.page(page1, queryWrapper);

        HashMap<String, Object> hashMap = new HashMap<>();

        hashMap.put("count", page1.getRecords().size());
        hashMap.put("currentPage", page);
        hashMap.put("data", page1.getRecords());
        hashMap.put("pageSize", limit);

        return ResultData.ok("", hashMap);
    }

}
